<?php
/**
 * desc: 产品字段业务处理类
 * Created by PhpStorm.
 * User: hc
 * Date: 2016/11/21
 * Time: 17:07
 */

namespace Home\Biz;


class FieldBiz
{


    /**
     * 查询
     * @param $field_code
     * @param $field_name
     */
    public static function searchField($field_code, $field_name)
    {
        $sql = "select id , field_code , field_name , unit , 
                (SELECT GROUP_CONCAT(option_value)FROM product_field_option  where field_id = f.id GROUP BY field_id) as option_value
                 from product_field f where 1=1";

        if (!empty($field_code)) {
            $sql = $sql . " AND f.field_code like '%$field_code%'";
        }

        if (!empty($field_name)) {
            $sql = $sql . " AND f.field_name like '%$field_name%'";
        }

        $sql = $sql." order by f.field_code asc";

        $result = M()->query($sql);

        return $result;

    }

    /**
     * 判断CODE是否已经存在
     * @param $field_code 字段code
     * @param $except_id id
     */
    public static function isCodeExsits($field_code, $except_id)
    {
        $condition = "";
        if (!empty($except_id)) {
            $condition = "AND id <> '$except_id'";
        }

        $result = M('product_field')->where("field_code ='$field_code'" . $condition)->select();
        if (sizeof($result) != 0) {
            return true;
        }

        return false;
    }

    /**
     * 查询详情
     * @param $id 主键
     */
    public static function getDetail($id)
    {
        $detail = M('product_field_option')->where("field_id='$id'")->select();
        return $detail;
    }

    /**
     * 保存Field
     * @param $field
     */
    public static function saveField($field, $field_options)
    {
        if (self::isCodeExsits($field['field_code'])) {
            return "字段CODE已经存在！";
        }
        M('product_field')->add($field);

        foreach ($field_options as $field_option) {
            $field_option['create_date'] = date("Y-m-d H:i:s", time());
            $field_option['create_user'] = cookie('login_user_id');
            $field_option['field_id'] = $field['id'];

            if (empty($field_option['id'])) {
                $field_option['id'] = self::generateFieldId();

                M('product_field_option')->add($field_option);
            } else {
                $option_id = $field_option['id'];
                M('product_field_option')->where("id='$option_id'")->save($field_option);
            }

        }

    }


    /**
     * 更新Field
     * @param $field
     */
    public static function updateField($field, $field_options)
    {
        $field_id = $field['id'];

        if (self::isCodeExsits($field['field_code'], $field_id)) {
            return "字段CODE已经存在！";
        }
        M('product_field')->where("id = '$field_id'")->save($field);

        foreach ($field_options as $field_option) {
            $field_option['create_date'] = date("Y-m-d H:i:s", time());
            $field_option['create_user'] = cookie('login_user_id');
            $field_option['field_id'] = $field['id'];

            if (empty($field_option['id'])) {
                $field_option['id'] = self::generateFieldId();

                M('product_field_option')->add($field_option);
            } else {
                $option_id = $field_option['id'];
                M('product_field_option')->where("id='$option_id'")->save($field_option);
            }

        }

    }


    /**
     * 根据optionId 删除选项值
     * @param $id
     * @return bool
     */
    public static function deleteOption($id)
    {
        $records = M('product_field_option')->where("id='$id'")->delete();
        if ($records == 0) return false;
        return true;
    }


    /**
     * 生成唯一主键
     * @return string
     */
    public static function generateFieldId()
    {
        $id = M()->query("select UUID() as uuid");
        return $id[0]['uuid'];
    }

    /**
     * @param $I
     * @return mixed
     */
    public static function loadOption($field_name)
    {
        $detail = M()->query("select option_value,((select unit from product_field where field_code ='$field_name'))as unit from product_field_option where field_id=(select id from product_field where field_code ='$field_name')");
        return $detail;
    }

    /**
     * 查询详情
     * @param $line_id
     */
    public static function loadDetail($line_id)
    {
        return M('product_line')->where("id = '$line_id'")->select();
    }

    public static function getGroup()
    {
        $group_names = CommonBiz::getGroup();
        $current_status = "";
        foreach ($group_names as $item) {
            $group_name = $item['group_name'];
            $mapping = C('PROCESS_LINE');
            $current_status = $mapping[$group_name];
            if ($current_status) return $group_name;
        }
    }

    /**
     * 保存产品信息
     * @param $field_line
     */
    public static function saveDetail($field_line)
    {

        //获取用户所属组-目前只取一个组
        $group_names = CommonBiz::getGroup();
        $current_status = "";
        foreach ($group_names as $item) {
            $group_name = $item['group_name'];
            $mapping = C('PROCESS_LINE');
            $current_status = $mapping[$group_name];
            if ($current_status) break;
        }

        //校验产品类型是否存在
        $exists = self::checkProductType($field_line['id'], $field_line['product_type']);
        if ($exists) {
            return "产品型号已经存在，请检查!";
        }

        if (empty($field_line['id'])) {


            $field_line['id'] = self::generateFieldId();
            //保存操作日志
            self::saveOperationLog($field_line['id'], '创建产品', array(), array());
            $field_line['process_flag'] = $current_status;
            M('product_line')->add($field_line);
        } else {
            $line_id = $field_line['id'];
            $status = M('product_line')->where("id='$line_id'")->select();


            //如果当前用户之前已经操作过则表示当前操作为更新否则为增补
            $flag = $current_status & $status[0]['process_flag'];
            $diff_origin = array_diff_assoc($status[0], $field_line);
            $diff_dest = array_diff_assoc($field_line, $status[0]);
            if ($flag == 0) {
                self::saveOperationLog($line_id, '增补', $diff_origin, $diff_dest);
            } else {
                self::saveOperationLog($line_id, '修改', $diff_origin, $diff_dest);
            }

            //按位或運算
            $field_line['process_flag'] = $current_status | $status[0]['process_flag'];
            M('product_line')->where("id='$line_id'")->save($field_line);
        }
    }

    /**
     * 查询产品线
     * @param $product_type
     * @return result
     */
    public static function queryProductLine($product_type, $index, $pageSize)
    {
        $condition_array = array();
        if (!empty($product_type)) {
            $condition_array['product_type'] = $product_type;
        }

        $product_line = M('product_line')->where($condition_array)->page($index, $pageSize)->select();

        // 总记录数
        $totalCount = M('product_line')->where($condition_array)->count();

        // 总页数
        $totalPage = self::caculateTotalPage($totalCount, $pageSize);
        // 下一页页码
        $nextIndex = $index + 1;
        // 上一页页码 如果是第一页，页码仍然为1
        $preIndex = 1;
        if ($index > 1) {
            $preIndex = $index - 1;
        }

        $resultMap = array(
            'totalCount' => $totalCount,
            'totalPage' => $totalPage,
            'nextIndex' => $nextIndex,
            'preIndex' => $preIndex,
            'index' => $index,
            'datas' => $product_line
        );

        return $resultMap;
    }

    public static function caculateTotalPage($totalCount, $pageSize)
    {

        $count = intval($totalCount / $pageSize);

        $countLeft = $totalCount % $pageSize;

        if ($countLeft != 0) {
            $count = $count + 1;
        }

        return $count;
    }

    /**
     * 审核
     * @param $line_id
     */
    public static function apply($line_id)
    {
        $details = self::loadDetail($line_id);
        $detail = $details[0];
        $appl = C('PROCESS_LINE.apply_group');
        $detail['process_flag'] = $detail['process_flag'] | $appl;
        M('product_line')->where("id='$line_id'")->save($detail);
    }

    /**
     * 保存操作日志
     */
    public static function saveOperationLog($line_id, $type, $diff_origin, $diff_dest)
    {
        $sql = "SELECT column_name,column_comment FROM information_schema.columns WHERE table_schema ='whaley_product'  AND table_name = 'product_line'";
        $colum_comments = M()->query($sql);
        $content = "";

        foreach ($diff_origin as $key => $value) {
            foreach ($colum_comments as $comment) {
                if ($comment['column_name'] == $key) {
                    $com = $comment['column_comment'];
                    $origin_value = $value;
                    $dest_value = $diff_dest[$key];
                    if ($origin_value != $dest_value) {
                        $content = $content . $com . ":[$origin_value => $dest_value]\r\n<br/>";
                    }

                    break;
                }
            }
        }

        $operation_log = array(
            'id' => self::generateFieldId(),
            'operation_type' => $type,
            'content' => $content,
            'operator' => cookie('login_user_id'),
            'operate_time' => date("y-m-d H:i:s", time()),
            'product_line_id' => $line_id
        );
        M('product_operation_log')->add($operation_log);
    }

    /**
     * 查询日志
     * @param $line_id
     * @return mixed
     */
    public static function findOperationLog($line_id)
    {
        return M('product_operation_log')->where("product_line_id = '$line_id'")->order('operate_time DESC')->select();
    }

    /**
     * 检查产品类型是否已经存在
     * @param $id 主键
     * @param $product_type 产品型号
     */
    private static function checkProductType($id, $product_type)
    {
        $condition = array();
        if (!empty($id)) {
            $condition['id'] = array('neq', $id);
        }
        if (!empty($product_type)) {
            $condition['product_type'] = $product_type;
        }

        $result = M('product_line')->where($condition)->select();
        if(sizeof($result) > 0){
            return true;
        }

        return false;
    }


}